/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.Logger;

/**
 *
 * @author PhucAn
 */
public class ServerUtil implements ServletContextListener {

    Logger log = Logger.getLogger(ServerUtil.class);

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext context = sce.getServletContext();
        InputStream is = context.getResourceAsStream("/WEB-INF/online_quiz_config.properties");
        Properties prop = new Properties();
        try {
            prop.load(is);
            String dbConnectionURL = prop.getProperty("db_url");
            String dbDriver = prop.getProperty("db_driver");
            String dbUser = prop.getProperty("db_user");
            String dbPassword = prop.getProperty("db_password");
            String mailServer = prop.getProperty("mail_server");
            String mailUser = prop.getProperty("mail_user");
            String mailPassword = prop.getProperty("mail_password");
            String mailPort = prop.getProperty("mail_port");
            context.setAttribute(SharingUtil.VAR_A_CONNECTION_URL, dbConnectionURL);
            context.setAttribute(SharingUtil.VAR_A_DB_DRIVER, dbDriver);
            context.setAttribute(SharingUtil.VAR_A_DB_USER, dbUser);
            context.setAttribute(SharingUtil.VAR_A_DB_PASSWORD, dbPassword);
            context.setAttribute(SharingUtil.VAR_A_MAIL_SERVER, mailServer);
            context.setAttribute(SharingUtil.VAR_A_MAIL_PORT, mailPort);
            context.setAttribute(SharingUtil.VAR_A_MAIL_USER_ID, mailUser);
            context.setAttribute(SharingUtil.VAR_A_MAIL_PASSWORD, mailPassword);
            DBUtil dbUtil = new DBUtil(context);
            log.info("InitServer: Online Quiz  server is initialized successfully");
        } catch (IOException ex) {
            log.info("Error when initialize server. " + ex.getMessage());
        } catch (Exception ex) {
            log.info("Error when initialize server. " + ex.getMessage());
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // throw new UnsupportedOperationException("Not supported yet.");
    }
}
